package com.ruoyi.customer.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.MapUtils;
import com.ruoyi.common.utils.redis.RedisUtils;
import com.ruoyi.customer.common.DisCustomerBo;
import com.ruoyi.customer.common.DisCustomerRequestBo;
import com.ruoyi.customer.common.DisVo;
import com.ruoyi.customer.domain.Customer;
import com.ruoyi.customer.domain.Remark;
import com.ruoyi.customer.domain.TotalComster;
import com.ruoyi.customer.mapper.CustomerMapper;
import com.ruoyi.customer.mapper.RemarkMapper;
import com.ruoyi.customer.mapper.TotalComsterMapper;
import com.ruoyi.customer.service.DisCommonService;
import com.ruoyi.customer.service.ITotalComsterService;
import com.ruoyi.disCustomer.domain.TCustomerDisRecord;
import com.ruoyi.disCustomer.mapper.TCustomerDisRecordMapper;
import com.ruoyi.enums.BusTypeEnum;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author suntf
 * @since 2023-08-24
 */
@RequiredArgsConstructor
@Service
public class TotalComsterServiceImpl implements ITotalComsterService {

    private final TotalComsterMapper totalComsterMapper;

    private final CustomerMapper customerMapper;

    private final RemarkMapper remarkMapper;

    private final DisCommonService disCommonService;

    private final TCustomerDisRecordMapper disRecordMapper;

    @Override
    public TableDataInfo<TotalComster> queryPageList(TotalComster bo, PageQuery pageQuery) {
        LambdaQueryWrapper<TotalComster> lqw = buildQueryWrapper(bo);
        Page page = new Page();
        page.setCurrent(pageQuery.getPageNum());
        page.setSize(pageQuery.getPageSize());
        Page<TotalComster> selectPage = totalComsterMapper.selectPage(page,
                lqw.orderByDesc(TotalComster::getCreateTime));
        return TableDataInfo.build(selectPage);
    }

    /**
     * 批量转移客户
     *
     * @param list
     * @return
     */
    @Transactional
    @Override
    public R transformerCustomer(List<Long> list) {
        if (CollectionUtils.isEmpty(list)) {
            return R.ok();
        }
        // 下发的时候保存备注信息
        String userId = LoginHelper.getLoginUser().getNickName();
        list.forEach(item -> {
            customerMapper.transformerCustomer(item, userId);
            totalComsterMapper.updateCustomer(item);

            // 查询一下 保存备注信息
            QueryWrapper<Customer> query = Wrappers.query();
            query.eq("deleted", 0);
            query.eq("total_customer_id", item);
            List<Customer> customers = customerMapper.selectList(query);
            if (!CollectionUtils.isEmpty(customers)) {
                for (Customer customer : customers) {
                    if (!StringUtils.isNotBlank(customer.getBz())) {
                        continue;
                    }
                    Remark remark = new Remark();
                    remark.setCustomerId(customer.getId());
                    remark.setContent(customer.getBz());
                    remark.setCreateBy(LoginHelper.getLoginUser().getNickName());
                    remark.setUserId(LoginHelper.getUserId());
                    remarkMapper.insert(remark);
                    // 保存下发记录
                    // 保存下推记录
                    TCustomerDisRecord disRecord = new TCustomerDisRecord();
                    disRecord.setBusType(BusTypeEnum.TOTAL_CUSTOMER.getCode());
                    disRecord.setCustomerId(customer.getId());
                    disRecord.setDisName("融·咨询");
                    // 分配给哪个部门
                    disRecord.setDisDeptId(100L);
                    disRecord.setCustomerName(customer.getName());
                    // 记录分配记录
                    disRecord.setOperateDisId(LoginHelper.getUserId());
                    disRecord.setOperateDeptId(LoginHelper.getDeptId());
                    disRecord.setOperateDisName(LoginHelper.getLoginUser().getNickName());
                    disRecord.setCreateTime(DateUtils.getNowDate());
                    disRecordMapper.insert(disRecord);
                }
            }
        });
        return R.ok();
    }

    @Override
    public R delCustomer(String id) {
        TotalComster totalComster = new TotalComster();
        totalComster.setDelFlag("1");
        totalComster.setUpdateBy(LoginHelper.getLoginUser().getNickName());
        totalComster.setUpdateTime(LocalDateTime.now());
        LambdaQueryWrapper<TotalComster> totalComsterQueryWrapper = new LambdaQueryWrapper<>();
        totalComsterQueryWrapper.eq(TotalComster::getDelFlag, "0");
        totalComsterQueryWrapper.eq(TotalComster::getId, id);
        this.totalComsterMapper.update(totalComster, totalComsterQueryWrapper);
        return R.ok();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public R updateRemark(TotalComster totalComster) {
        if (CollectionUtils.isEmpty(totalComster.getIds())) {
            return R.fail("请选择更新数据!");
        }
        String remarkInfo = totalComster.getRemark();

        String remark =
                remarkInfo + "--" + LoginHelper.getLoginUser().getNickName() + "[" + DateUtils.parseDateToStr(
                        DateUtils.YYYY_MM_DD_HH_MM_SS, DateUtils.getNowDate()) + "]";
        List<Long> ids = totalComster.getIds();
        // 更新三张表
        String tmpTable = Constants.TMPTABLENAME + totalComster.getBatchLogo();
        ids.forEach(item -> {
            // 更新临时库和总库
            totalComsterMapper.updateTotalRemark(item, remark, tmpTable);
            // 查询一下在t_customer表中的备注
            Integer cnt = totalComsterMapper.updateCustomerRemark(item, remark, tmpTable);
            if (cnt > 0) {
                // 查询t_customer主键 删除缓存和更新日志表
                Map<String, String> customerId = customerMapper.getCustomerId(item, tmpTable);
                String id = MapUtils.getDefaultValueByKey(customerId, "id", "0");
                remarkMapper.deleteRemark(id, LoginHelper.getLoginUser().getNickName());
                //RedisUtils.deleteKeys(CacheConstants.CUSTOMER_BZ_KEY + id);

                // 新增备注信息
                Remark remark1 = new Remark();
                remark1.setContent(remark);
                remark1.setCustomerId(Long.valueOf(id));
                remark1.setCreateBy(LoginHelper.getLoginUser().getNickName());
                remark1.setUserId(LoginHelper.getUserId());
                remarkMapper.insert(remark1);
            }
        });
        return R.ok();
    }

    @Override
    public R updateCustomerName(TotalComster totalComster) {
        if (CollectionUtils.isEmpty(totalComster.getIds())) {
            return R.fail("请选择更新数据!");
        }
        String customerName = totalComster.getCustomerName();
        List<Long> ids = totalComster.getIds();
        // 更新三张表
        String tmpTable = Constants.TMPTABLENAME + totalComster.getBatchLogo();
        ids.forEach(item -> {
            // 更新临时库和总库
            totalComsterMapper.updateTotalCustomerName(item, customerName, tmpTable);
            // 查询一下在t_customer表中的姓名
            Integer cnt = totalComsterMapper.updateCustomerName(item, customerName, tmpTable);
        });

        return R.ok();
    }

    @Override
    public R updateCustomerStatus(TotalComster totalComster) {
        String customerStatus = totalComster.getCustomerStatus();
        List<Long> ids = totalComster.getIds();
        // 更新三张表
        String tmpTable = Constants.TMPTABLENAME + totalComster.getBatchLogo();
        ids.forEach(item -> {
            // 更新临时库和总库
            totalComsterMapper.updateTotalCustomerStatus(item, customerStatus, tmpTable);
            // 查询一下在t_customer表中的状态
            Integer cnt = totalComsterMapper.updateCustomerStatusNew(item, customerStatus, tmpTable);
        });
        return R.ok();
    }

    @Override
    public R updateCustomerLevel(TotalComster totalComster) {
        if (CollectionUtils.isEmpty(totalComster.getIds())) {
            return R.fail("请选择更新数据!");
        }
        String customerLevel = totalComster.getCustomerLevel();
        List<Long> ids = totalComster.getIds();
        // 更新三张表
        String tmpTable = Constants.TMPTABLENAME + totalComster.getBatchLogo();
        ids.forEach(item -> {
            // 更新临时库和总库
            totalComsterMapper.updateTotalCustomerLevel(item, customerLevel, tmpTable);
            // 查询一下在t_customer表中的星级
            Integer cnt = totalComsterMapper.updateCustomerLevel(item, customerLevel, tmpTable);
        });
        return R.ok();
    }

    @Override
    @Transactional
    public R oneKeyIssueToDept(DisCustomerRequestBo keyIssueBo,String operationType) {
        List<DisCustomerBo> disCustomerBos = disCommonService.checkDataDept(keyIssueBo,
                operationType);
        List<DisVo> disVos = disCommonService.dataDealDept(disCustomerBos, keyIssueBo.getDeptBos());
        disCommonService.disToDept(disVos, operationType, LoginHelper.getLoginUser().getNickName(), LoginHelper.getUserId(), LoginHelper.getDeptId());
        return R.ok();
    }

    @Override
    @Transactional
    public R oneKeyIssueToUser(DisCustomerRequestBo keyIssueBo , String operationType) {
        List<DisCustomerBo> disCustomerBos = disCommonService.checkDataUser(keyIssueBo,
                operationType);
        // 操作分配
        List<DisVo> disVos = disCommonService.dataDealUser(disCustomerBos, keyIssueBo.getUserBos());

        //Map<String, Object> map = disCommonService.userDataDeal(disVos);
       // List<DisVo> successList = (List<DisVo>) map.get("success");
        disCommonService.disToUser(disVos, operationType, LoginHelper.getLoginUser().getNickName(), LoginHelper.getUserId(), LoginHelper.getDeptId());

//        disCommonService.sentInfo(Constants.DIS_MESSAGE, map);
        return R.ok();
    }

    private LambdaQueryWrapper<TotalComster> buildQueryWrapper(TotalComster bo) {
        LambdaQueryWrapper<TotalComster> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getName()), TotalComster::getName, bo.getName());
        lqw.like(StringUtils.isNotBlank(bo.getStatus()), TotalComster::getStatus, bo.getStatus());
        lqw.like(StringUtils.isNotBlank(bo.getSource()), TotalComster::getSource, bo.getSource());
        lqw.like(StringUtils.isNotBlank(bo.getRemark()), TotalComster::getRemark, bo.getRemark());
        lqw.like(StringUtils.isNotBlank(bo.getMobile()), TotalComster::getMobile, bo.getMobile());
        lqw.like(StringUtils.isNotBlank(bo.getBatchLogo()), TotalComster::getBatchLogo, bo.getBatchLogo());
        lqw.ge(StringUtils.isNotBlank(bo.getStartTime()), TotalComster::getCreateTime, bo.getStartTime());
        lqw.le(StringUtils.isNotBlank(bo.getEndTime()), TotalComster::getCreateTime, bo.getEndTime());
        lqw.eq(StringUtils.isNotBlank(bo.getFlag()), TotalComster::getCustomerFlag, bo.getFlag());
        lqw.eq(StringUtils.isNotBlank(bo.getDelFlag()), TotalComster::getDelFlag, bo.getDelFlag());
        lqw.eq(StringUtils.isNotBlank(bo.getLevel()), TotalComster::getLevel, bo.getLevel());
        String channelIds = bo.getChannelIds();
        if (StringUtils.isNotBlank(bo.getChannelIds())) {
            channelIds = "," + channelIds + ",";
            lqw.like(TotalComster::getChannelIds, channelIds);
        }
        String currentType = bo.getCurrentType();
        // 1、总库登录 2、待下发列表信息
        if (!Objects.equals("1", currentType)) {
            // flag 为0
            lqw.eq(TotalComster::getCustomerFlag, "0");
        }
        return lqw;
    }
}
